<template>
  <div></div>
</template>

<script lang="ts" setup>
import emptyMp3 from "@/assets/sound/empty.mp3";
import newGroupMp3 from "@/assets/sound/newGroup.mp3";
import newNoticeMp3 from "@/assets/sound/newNotice.mp3";
import msgSoundMp3 from "@/assets/sound/msgSound.mp3";
import resultMp3 from "@/assets/sound/result.mp3";
import { SoundName } from "@/enums";
import { showDialog } from "vant";

const state = reactive({
  audio: <HTMLAudioElement>new Audio(emptyMp3),
  emptyAudio: new Audio(emptyMp3),
  newGroupAudio: new Audio(newGroupMp3),
  newNoticeAudio: new Audio(newNoticeMp3),
  msgSoundAudio: new Audio(msgSoundMp3),
  resultAudio: new Audio(resultMp3)
});

const setSound = (name?: SoundName) => {
  switch (name) {
    case SoundName.newGroup:
      return state.newGroupAudio;
    case SoundName.newNotice:
      return state.newGroupAudio;
    case SoundName.msgSound:
      return state.msgSoundAudio;
    case SoundName.result:
      return state.resultAudio;
    default:
      return state.emptyAudio;
  }
};

const play = async (name?: SoundName) => {
  state.audio = setSound(name);
  nextTick(() => {
    if (window.sound) {
      pause();
      // 如果能自动播放，取消静音并播放
      state.audio.muted = false;
      state.audio.currentTime = 0;
      state.audio.play();
    } else {
      showDialog({
        message: "允许播放声音"
      }).then(() => {
        state.audio.muted = false;
        state.audio.currentTime = 0;
        state.audio.play();
        window.sound = true;
      });
    }
  });
};

const pause = () => {
  if (state.audio) {
    state.audio.pause();
  }
};

const setVolume = (v: number) => {
  if (state.audio) {
    state.audio.volume = v;
  }
};

onMounted(() => {
  setSound();
});

defineExpose({
  play,
  pause,
  setVolume
});
</script>
